﻿using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using Object = System.Object;

namespace CxExtension
{
	public static class ObjectReflectExt
	{
		public static BindingFlags default_flags = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance;
		public static BindingFlags default_Allflags = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance |BindingFlags.NonPublic |BindingFlags.ExactBinding |BindingFlags.Static;
		/// <summary>
		/// 设置某个名字的属性
		/// </summary>
		/// <param name="self"></param>
		/// <param name="propertyName"></param>
		/// <param name="value"></param>
		/// <param name="flags"></param>
		public static void SetProperty(this object self,string propertyName,string value,BindingFlags flags = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance)
		{
			Type type = self.GetType();
			var property = type.GetProperty(propertyName,flags);
			if(property == null)
				return;
			var pro_type = property.PropertyType;
			var value1 = value.ParseValue(pro_type);
			property.SetValue(self,value1,null);
		}

		/// <summary>
		/// 调用指定名称的函数,没有返回值
		/// </summary>
		/// <param name="self"></param>
		/// <param name="name"></param>
		/// <param name="overrideType">The call func type</param>
		/// <param name="args"></param>
		public static object Call(this object self, string name,Type overrideType, params object[] args)
		{
			var methon = overrideType.GetMethodByCache(name);
			if (methon == null)
			{
				return null;
			}

			return methon.Invoke(self, args);
		}

		/// <summary>
		/// 调用指定名称的函数,没有返回值
		/// </summary>
		/// <param name="self"></param>
		/// <param name="name"></param>
		/// <param name="args"></param>
		public static object Call(this object self,string name,params object[] args)
		{
			return self.Call(name, self.GetType(), args);
		}

		public static object CallStatic<T>(string name, params object[] args)
		{
			var type = typeof(T);
			return type.CallStatic(name, args);
		}

		public static object CallStatic(this Type type,string name, params object[] args)
		{
			var moth = type.GetMethodByCache(name);
			if (moth == null)
			{
				return null;
			}

			return moth.Invoke(null, args);
		}
		public static object CallStaticT(this Type type,string name, Type[] paramTypes = null, params object[] args)
		{
			var moth = type.GetMethodByCache(name,paramTypes);
			if (moth == null)
			{
				return null;
			}

			return moth.Invoke(null, args);
		}

		public static int GetIntValue(this object self)
		{
			var obj = (int)self;
			return obj;
		}

		public static void SetValue(this object self,Dictionary<string,string> map)
		{
			foreach(var item in map)
			{
				try
				{
					self.SetProperty(item.Key,item.Value);
				}
				catch(Exception e)
				{
					Debug.LogErrorFormat("读取配置失败 class = {0},id = {3},key = {1},value = {2}",self.GetType().Name,item.Key,item.Value,map["id"]);
					throw e;
				}
			}
		}
	}
}